package com.eexcel.workbench;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.e4.core.di.annotations.Execute;
/**
 * Defines the handler who evaluates the contributions to the plugin 
 * @author simão Fernandes et al.
 * @version %I%, %G%
 * @since 1.0
 */
public class EvaluateContributionsHandler {
	private static final String IFORMULA_ID = "com.eexcel.workbench.formula";

	/**
	 * Executes the evaluation
	 * @param registry ExtensionRegistry reference
	 */
	@Execute
	public void execute(IExtensionRegistry registry) {
		evaluate(registry);
	}
	
	/**
	 * Evaluates the contributions
	 * @param registry ExtensionRegistry reference
	 */
	private void evaluate(IExtensionRegistry registry) {
		IConfigurationElement[] config = registry
				.getConfigurationElementsFor(IFORMULA_ID);
		try {
			for (IConfigurationElement e : config) {
				System.out.println("Evaluating extension");
				final Object o = e.createExecutableExtension("class");
				if (o instanceof IFormula) {
					executeExtension(o);
				}
			}
		} catch (CoreException ex) {
			System.out.println(ex.getMessage());
		}
	}
	
	/**
	 * Executes the contributing extension
	 * @param o Reference to the contributing instance
	 */
	private void executeExtension(final Object o) {
		ISafeRunnable runnable = new ISafeRunnable() {
			@Override
			public void handleException(Throwable e) {
				System.out.println("Exception in client");
			}

			@Override
			public void run() throws Exception {
				int fib = ((IFormula) o).calculate("fib", 6);
				System.out.println("Fibonacci: " + fib);
			}
		};
		SafeRunner.run(runnable);
	}
}
